package com.rem.designPattern.prototype原型.deepclone2;

import java.io.*;

/**
 * 深拷贝：1.复制对象的所有基本数据类型的成员变量值
 * *      2.为所有引用数据类型的成员变量申请存储空间，并复制每个引用数据类型成员变量所引用的对象，直到该对象可达的所有对象
 * 深拷贝-通过对象序列化实现深拷贝
 *
 * @author Rem
 * @date 2022-11-15
 */
public class Sheep implements Serializable {

    private String name;
    private int age;

    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

class Shepherd implements Serializable {

    private String name;

    private Sheep sheep;

    public Shepherd(String name, Sheep sheep) {
        this.name = name;
        this.sheep = sheep;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Sheep getStudent() {
        return sheep;
    }

    public void setStudent(Sheep sheep) {
        this.sheep = sheep;
    }

    public Shepherd deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return (Shepherd) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}